<?php

namespace app\command;

use app\common\model\PhonePoolModel;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use Workerman\Worker;

class Timer extends Command
{
    /**
     * @var int
     */
    protected $timer;

    protected $interval = 2;

    protected function configure()
    {
        // 指令配置
        $this->setName('timer')
            ->addArgument('status', Argument::REQUIRED, 'start/stop/reload/status/connections')
            ->addOption('d', null, Option::VALUE_NONE, 'daemon（守护进程）方式启动')
            ->addOption('i', null, Option::VALUE_OPTIONAL, '多长时间执行一次,可以精确到0.001')
            ->setDescription('start/stop/restart 定时任务');
    }

    protected function init(Input $input, Output $output)
    {
        global $argv;

        if ($input->hasOption('i')) {
            $this->interval = floatval($input->getOption('i'));
        }

        $argv[1] = $input->getArgument('status') ?: 'start';
        if ($input->hasOption('d')) {
            $argv[2] = '-d';
        } else {
            unset($argv[2]);
        }
    }

    protected function execute(Input $input, Output $output)
    {
        $this->init($input, $output);

        $worker = new Worker();
        $worker->count = 2;//进程

        $worker->onWorkerStart = [$this, 'start'];
        $worker->runAll();
    }

    public function stop()
    {
        \Workerman\Lib\Timer::del($this->timer);
    }

    public function start()
    {
        $this->timer = \Workerman\Lib\Timer::add($this->interval, [$this, 'offline']);
    }

    public function offline()
    {
        $this->output->writeln(date('YmdHis'));
        $data = PhonePoolModel::order('id')->find();
        if ($data){
            if (!cmf_check_mobile($data['phone'])){
                $data->delete();
            }

            if ($data['create_time'] + 4800 < time()){
                $data->delete();
            }

        }
    }


}
